package com.yanqu.road.server.cmd.disperseGold;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.disperseGold.DisperseGoldGroupUser;
import com.yanqu.road.entity.enums.eDecorationType;
import com.yanqu.road.entity.enums.eHonoraryTitleType;
import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.player.UserBadge;
import com.yanqu.road.entity.servercenter.GameEditLimit;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.disperseGold.DisperseGoldProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.curio.CurioModule;
import com.yanqu.road.server.gameplayer.module.assistant.AssistantSkinModule;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.BadgeModule;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.manger.ForbiddenMgr;
import com.yanqu.road.server.manger.ForbiddenWordMgr;
import com.yanqu.road.server.manger.GameEditLimitMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.ActivityInfoMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.player.DisperseGoldMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Cmd(code = Protocol.S_DISPERSEGOLD_DISPERSE , desc = "送财")
public class DisperseGoldCmd extends AbstractCommand {
    private String manifesto;
    private int skinType;           //4.4新增小玉皮肤送财 0为主角皮肤,1为小玉皮肤
    private int showBadge;          //是否展示徽章  0 不展示 1为展示
    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        DisperseGoldProto.DisperseGoldReqMsg reqMsg = DisperseGoldProto.DisperseGoldReqMsg.parseFrom(packet.getBytes());
        manifesto = reqMsg.getManifesto();
        if (reqMsg.hasSkinType()){
            skinType = reqMsg.getSkinType();
        }else {
            skinType = 0;
        }
        if (reqMsg.hasShowBadge()) {
            showBadge = reqMsg.getShowBadge();
        } else {
            showBadge = 0;
        }
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        //编辑限制
        GameEditLimit gameEditLimit = GameEditLimitMgr.getGameEditLimit(Protocol.S_DISPERSEGOLD_DISPERSE);
        if(null != gameEditLimit){
            long nowTime = System.currentTimeMillis();
            if(nowTime >= gameEditLimit.getLimitEditStartTime() && nowTime < gameEditLimit.getLimitEditEndTime()){
                String replaceStr = "祝掌柜们财源广进！";
                if(!StringUtils.isNullOrEmpty(gameEditLimit.getReplaceContent())){
                    replaceStr = gameEditLimit.getReplaceContent();
                }
                manifesto = replaceStr;
            }
        }
        /**
         * 送财功能被禁用 则返回系统未开放
         */
        if(ForbiddenMgr.isForbiddenCmd(player.getUserId(), Protocol.S_DISPERSEGOLD_DISPERSE)) {
            ret = GameErrorCode.E_SYSTEM_NO_OPEN;
            return;
        }

        DecorationModule decorationModule = player.getModule(DecorationModule.class);
        List<Integer> decorationIdList = decorationModule.getDecorationIdList(eDecorationType.HonoraryTitle.getValue());
        if (decorationIdList == null || decorationIdList.isEmpty()) {
            ret = GameErrorCode.E_DISPERSEGOLD_NOT_UNLOCK;
            return;
        }
        long times = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.DisperseGold);
        if (times >= GameConfig.DISPERSE_GOLD_DAY_TIMES) {
            ret = GameErrorCode.E_DISPERSEGOLD_NOT_TIMES;
            return;
        }
        if (StringUtils.isNullOrEmpty(manifesto)) {
            ret = GameErrorCode.E_DISPERSEGOLD_MANIFESTO_NULL;
            return;
        }
        if (ForbiddenWordMgr.isForbidden(manifesto)) {
            ret = GameErrorCode.E_DISPERSEGOLD_FORBIDDEN;
            return;
        }

        String assistantSkinString = "";
        if (skinType == 1) {                         //1为小玉形象送财请求
            if (!SystemOpenMgr.systemOpen(player, eSystemId.Assistant.getValue())) {
                ret = GameErrorCode.E_ASSISTANT_SKIN_SYSTEM_NO_UNLOCK;
                return;
            }
            if (player.getModule(AssistantSkinModule.class).getTotalDressValue() < GameConfig.ASSISTANT_PRAY_UNLOCK) {
                ret = GameErrorCode.E_ASSISTANT_SKIN_DISPERSE_DRESS_VALUE_NO_ENOUGH;
                return;
            }
            assistantSkinString = player.getModule(AssistantSkinModule.class).getCollocationString();
        }
        String badge = "";
        if (showBadge == 1) {
            UserBadge disperseGoldShowBadge = player.getModule(BadgeModule.class).getDisperseGoldShowBadge();
            if (disperseGoldShowBadge!=null) {
                badge = disperseGoldShowBadge.getBadgeId() + "," + disperseGoldShowBadge.getBadgeType();
            }
        }
        //计算是否需要跨服
        Set<Long> ids = new HashSet<>();
        // 商会分组的需要按名单来
        List<DisperseGoldGroupUser> groupUserList = new ArrayList<>();
        int curChannelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
        for (Integer decorationId : decorationIdList) {
            // 类型过滤
            int type = decorationModule.getHonoraryTitleType(decorationId);
            if (type == eHonoraryTitleType.Local.getValue()) {
                // 本服加进去
                ids.add(GameServer.getInstance().getServerId());
                continue;
            }
            boolean isUnionGroup = false;
            int activityId = decorationModule.getActivityId(decorationId);
            ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(activityId);
            if (activityInfo != null) {
                // 空字符串、null、0、1都表示分1组，按旧活动逻辑走
                String unionGroup = activityInfo.getUnionGroup();
                if (StringUtils.isNullOrEmpty(unionGroup) || "0".equals(unionGroup) || "1".equals(unionGroup)) {
                    isUnionGroup = false;
                } else {
                    isUnionGroup = true;
                }
            }
            if (type != eHonoraryTitleType.Cross.getValue() && type != eHonoraryTitleType.Area.getValue()) {
                continue;
            }
            if (isUnionGroup) {
                // 商会分组
                UnionActivityGroup groupData = GameUnionActivityGroupMgr.getDbGroupData(activityId, player.getUserId());
                if (groupData != null) {
                    // 商会分组涉及名单
                    for (UnionActivityGroupUnion union : groupData.getUnionDataMap().values()) {
                        for (UnionActivityGroupUser groupUser : union.getUserMap().values()) {
                            groupUserList.add(new DisperseGoldGroupUser(groupUser.getServerId(), groupUser.getUserId()));
                        }
                    }
                }
            } else {
                // 旧逻辑
                // 区服ID判断
                List<Long> serverIds = decorationModule.getServerIds(decorationId);
                if (serverIds != null) {
                    for (Long serverId : serverIds) {
                        // 跨服称号不能送跨地区
                        int channelId = ServerListMgr.getChannelId(serverId);
                        if (channelId != curChannelId && type != eHonoraryTitleType.Area.getValue()) {
                            continue;
                        }
                        ids.add(serverId);
                    }
                }
            }
        }
        // 玩家藏品特权
        int curioPrivilegeItemId = player.getModule(CurioModule.class).getDisperseGoldPrivilegeItem();
        // 发送完次数增加
        player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.DisperseGold, times + 1);
        DisperseGoldMgr.sendDisperseGoldMsg(player.getUserInfo(), manifesto, decorationIdList, ids, groupUserList, assistantSkinString, badge, curioPrivilegeItemId);
    }

    @Override
    public void sendData(GamePlayer player) {
        DisperseGoldProto.DisperseGoldRespMsg.Builder respMsg = DisperseGoldProto.DisperseGoldRespMsg.newBuilder();
        respMsg.setRet(ret);
        player.sendPacket(Protocol.U_DISPERSEGOLD_DISPERSE, respMsg);
    }
}
